using System;
using System.Runtime.InteropServices;
using System.Diagnostics;


namespace Deamon
{

    class Program
    {
        [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)]
        private extern static bool ShowWindow(IntPtr hWnd, Int16 nCmdShow);

        public static String fn { get; set; }

        static void Main(string[] args)
        {
            Console.Title = "deamon";
            string doc = @"     
        date:2021年5月4日
        author：robotwu
        读取第一个参数启动程序（支持守护*.bat脚本,*.py等等），守护进程防止退出，需要安装.net 2.0 or later
        如果不结束守护程序，是无法退出被守护的进程，不要做非法用途。
        启动例子：deamon notepad.exe ";

            if (args.Length > 0)
            {
                IntPtr hWnd = FindWindow("ConsoleWindowClass", "deamon");
                while (!ShowWindow(hWnd, 0))
                {
                    System.Threading.Thread.Sleep(50);
                    hWnd = FindWindow("ConsoleWindowClass", "deamon");
                }
                fn = args[0];
                Program p = new Program();
                p.Launch(fn);

            }
            else
            {
                Console.WriteLine(doc);

            }
            Console.ReadKey();

        }


        public void Launch(String FileName)
        {
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = FileName;

            Process p = new Process();
            p.StartInfo = psi;
            p.EnableRaisingEvents = true;
            p.Exited += LaunchAgain;

            p.Start();

        }

        public void LaunchAgain(object o, EventArgs e)
        {
            Launch(fn);
        }

    }
}
